<script lang="ts" setup>
import {ref,onMounted,reactive} from 'vue'
import { useRoute, useRouter } from "vue-router";
import {year,quarter,month,industry,keynote} from '@/views/allData/zhibiao'
import upfiles from '@/components/upfiles.vue';
import type { FormInstance ,TabsPaneContext} from 'element-plus'
import { ElMessage } from 'element-plus'
import { reportfindById, reportpublish, getLast, editReports} from "@/util/api";
import { useStore } from '@/store'
const ruleFormRef = ref<FormInstance>();
const store = useStore()
const router = useRouter()
const users = store.state.userInfo
const query = useRoute().query
const id:any = ref("")
const isCheck:any=ref(false)
const templateId:any = ref('')//报表类型
const tabs:any = ref('')//展示的tab
const showZb:any = ref([])//展示的指标
const dataCopy:any = ref({})//报表原始数据
const loading = ref(false)
const nowtableNo = ref('')
const form = ref({
    tableData: <any>[],
    infoMsg:<any>{}
})
const rules = reactive({
    value: [
      { required: true, message: '请输入本期实际值', trigger: 'blur' },
    ],
    last: [
      { required: true, message: '请输入往期实际值', trigger: 'blur' },
    ],
    leader: [
      { required: true, message: '请输入单位负责人', trigger: 'blur' },
    ],
    statistical: [
      { required: true, message: '请输入统计负责人', trigger: 'blur' },
    ],
    preparer: [
      { required: true, message: '请输入填表人', trigger: 'blur' },
    ],
    tel: [
      { required: true, message: '请输入联系电话', trigger: 'blur' },
    ],
    phone: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
    ],
    date: [
      { required: true, message: '请输入报出日期', trigger: 'blur' },
    ],
  })
const reportType = {
    month:['1'],
    quarter:['2','5'],
    year:['3','4'],
    industry:['6'], 
    keynote:['7']
}
const getLastValue = async()=>{
   let res:any = await getLast(query.id)
//    console.log(res)
   if(!res.data[0])return ElMessage.error('往期未填值')
   let lastdata = JSON.parse(res.data[0])
//    console.log(lastdata)
   showZb.value.forEach((v:any)=>{
    lastdata.forEach((item:any)=>{
                if(v.sort==item.sort){
                    v['last'] = item.value
                }
            })
   })
}
const getTable = async()=>{
     loading.value = true
     let res:any = await reportfindById(query.id)
     console.log(JSON.parse(res.data.list))
     dataCopy.value = res.data
     let list = res.data.list
     form.value.tableData = showZb.value
     if(res.data.list!=null&&res.data.list!='null'){
        list = JSON.parse(res.data.list)
        // console.log(list[0])
        form.value.tableData.forEach((v:any)=>{
            v['sort']=v.sort
            list.forEach((item:any)=>{
                if(v.sort==item.sort){
                    if(item.last){
                        v.last = item.last.replace(/\s+/g,"");
                    }
                    if(item.value){
                        // console.log(item.value)
                        v.value = item.value.replace(/\s+/g,"");
                    }
                    v.isYG1 = item.isYG1;
                    v.remark1 = item.remark1;
                    v.ratio1 = item.ratio1;
                    v.remark = item.remark
                }
            })
        })
     }
     if(res.data.info!=null&&res.data.info!='null'){
        form.value.infoMsg = JSON.parse(res.data.info) 
        form.value.infoMsg['tableNo'] = nowtableNo.value
     }
     form.value.infoMsg.title=res.data.name
     loading.value = false
}
//返回
const goback = () => {
    router.push('/monthReport')
}
//保存报表
const  savebg= async() => {
    saveInfo()
    console.log(JSON.parse(dataCopy.value.list) )
     let res:any = await editReports(dataCopy.value)
     if(res.code=='200')ElMessage.success('已保存') 
}
const saveInfo=()=>{
    if(!form.value.infoMsg.time){
        form.value.infoMsg.time = getCurrentTime()
    }
    if(!form.value.infoMsg.agencyName||form.value.infoMsg.agencyName==null){
        form.value.infoMsg.agencyName = dataCopy.value.developArea
    }
    dataCopy.value.info = JSON.stringify(form.value.infoMsg)
    dataCopy.value.list = JSON.stringify(form.value.tableData)
}
//上报
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
    if (!valid) return ElMessage.error('请填写完整再上报')    
    console.log(form.value.tableData)
    if(dataCopy.value.filesQ==null)return ElMessage.error('请先左上角上传文件')
    saveInfo()
    editReports(dataCopy.value).then(async (saves:any)=>{
        if(saves.code!='200')return
        let res:any= await reportpublish(id.value)
        if(res.code=='200'){
            router.push('/monthReport')
        }  
    })
    
    })
  }



  const  repair=(i:any)=>{
    if (i >= 0 && i <= 9) {
        return "0" + i;
    } else {
        return i;
    }
}
  const  getCurrentTime=()=> {
    var date = new Date();//当前时间
    var year = date.getFullYear() //返回指定日期的年份
    var month = repair(date.getMonth() + 1);//月
    var day = repair(date.getDate());//日
    //当前时间 
    var curTime = year + "-" + month + "-" + day;
    return curTime;
}
const stopScrollFun=(evt:any)=>{  
  evt = evt || window.event;  
    if(evt.preventDefault) {  
    // Firefox  
      evt.preventDefault();  
      evt.stopPropagation();  
    } else {  
      // IE  
      evt.cancelBubble=true;  
      evt.returnValue = false;  
  }  
  return false;  
}
 const returnRatio=(a:any,b:any)=>{
     a = Number(a)
     b = Number(b)
     if(!a){
        a=0
     }
     if(!b){
        b=0
     }
     if(a<0&&b<0) return '/'
     if(a<0&&b>0) return '-100%'
     if(a>0&&b<0) return '—'
     if(a==0&&b==0)return '/'
     if(a==0&&b>0)return '-100%'
     if(a>0&&b==0)return '—'
     if(a==0&&b<0)return '—'
     if(a<0&&b==0)return '/'
     let ratio:any = ''
    //  ratio = ((a-b)/b)*100 +'%'
     ratio = (((a-b ) / b)*100).toFixed(2)+'%'
     return ratio
 } 
 const handleClick = (tab: TabsPaneContext, event: Event) => {
    getTable()
}
onMounted(()=>{
    templateId.value= query.radio1
    tabs.value = query.tabs
    id.value = query.id
    if(query.isCheck){
        isCheck.value=true
    }else{
        isCheck.value=false
    }
    if(reportType.month.includes(templateId.value)){
        showZb.value = month
        nowtableNo.value= "经开区统1表"
    }else if(reportType.quarter.includes(templateId.value)){
        showZb.value = quarter
        nowtableNo.value = "经开区统2表"
    }else if(reportType.year.includes(templateId.value)){
        showZb.value = year
        nowtableNo.value = "经开区统3表"
    }else if(reportType.industry.includes(templateId.value)){
        showZb.value = industry
        nowtableNo.value = "经开区统1表"
    }else if(reportType.keynote.includes(templateId.value)){
        showZb.value = keynote
        nowtableNo.value = "经开区统2表"
    }
    getLastValue()
    getTable()
})
const handleChangeCellStyle =({row, column, rowIndex, columnIndex})=>{
     if(column.no==0){
        return { color: "#189EFF" };
     }
}
</script>
<template>
     <el-tabs v-model="tabs" class="demo-tabs" @tab-click="handleClick"
      style="width: 98%;;background: #fff;padding: 20px;box-sizing: border-box;">
      <el-tab-pane label="表单设计" name="first">
        <el-form label-position="right" label-width="0" :model="form" style="width: 100%;" ref="ruleFormRef" :rules="rules">
        <div class="bth-report" v-if="!isCheck">
            <el-button @click="goback"  type="primary">返回</el-button>
            <el-button @click="savebg"  type="primary">保存</el-button>
            <el-button @click="submitForm(ruleFormRef)" v-if="users.userRole!='1'" type="primary">上报</el-button>
        </div>
        <div class="table-box">
            <div class="table-title">
                {{ form.infoMsg.title }}
            </div>
            <div class="msg-box">
                <div style="width: 30%">
                <div class="enact"><span class="enact-first">表&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号:</span><span>{{form.infoMsg.tableNo}}</span></div>
                <div class="enact"><span class="enact-first">制定机关:</span>陕西省商务厅<span></span></div>
                <div class="enact"><span class="enact-first">批准机关:</span>陕西省统计局<span></span></div>
                <div class="enact"><span class="enact-first">批准文号:</span>陕统函〔2022〕35号<span></span></div>
                <div class="enact"><span class="enact-first">有效期至:</span>2025年4月<span></span></div>
                <div class="enact"><span class="enact-first" style="line-height: 32px;">时&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;间:</span><span>
                    <el-date-picker
                        :disabled="isCheck"
                        v-model="form.infoMsg.time"
                        placeholder="年-月-日"
                        style="width: 200px;"
                        format="YYYY-MM-DD"
                        type="date"
                        value-format="YYYY-MM-DD"
                        />
                </span></div>
                </div>
            </div>
            <div class="agencyName">综合机关名称：<el-input  style="width: 160px;" v-model="form.infoMsg.agencyName" :disabled="isCheck" placeholder="" /></div>
            <el-table 
            border 
            :data="form.tableData"
            v-loading="loading"
             style="width: 100%;" 
             :header-cell-style="{
                background: '#E7F2FF',
                color: 'black',
                height:'60px',
                borderBottom: '1px solid rgb(102, 102, 102)',
                }"
                :cell-style="handleChangeCellStyle">
                <el-table-column v-if="templateId=='6'||templateId=='7'" label="行业代码" width="90" >
                    <template #default="scope">
                    <div>{{ scope.row.code }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="指标名称" width="400" show-overflow-tooltip >
                 <template #default="scope">
                 <div :style="{'text-indent':(scope.row.indent*10)+'px'}">{{ scope.row.name }}</div>
                </template>
                </el-table-column>
                <el-table-column prop="unit" label="计量单位" width="200" />
                <el-table-column prop="sort" label="代码"  width="100"/>
                <el-table-column  label="本期实际值" width="200">
                    <template #default="{row,$index}">
                        <el-form-item :prop="`tableData.${$index}.value`" :rules="rules.value">
                        <el-input type="number" style="width: 100%;" v-model="row.value" :disabled="isCheck" placeholder="" @wheel="stopScrollFun" />
                        </el-form-item>
                    </template>
                </el-table-column>
                <el-table-column label="预估数标注" width="auto"  align="center">
                    <template #default="scope">
                        <el-checkbox v-model="scope.row.isYG1" size="large" :disabled="isCheck" />
                    </template>
                </el-table-column>
                <el-table-column label="备注"  width="400">
                    <template #default="scope">
                        <el-input  style="width: 100%;" v-model="scope.row.remark" :disabled="isCheck" placeholder="" />
                    </template>
                </el-table-column>
                <el-table-column  label="往期实际值"  width="200">
                    <template #default="{row,$index}">
                        <el-input type="number" style="width: 100%;" v-model="row.last" :disabled="isCheck||users.userRole=='3'" placeholder="" />
                    </template>
                </el-table-column>
                
                <el-table-column label="同比"  width="150">
                <template #default="scope">
                       <div>{{ returnRatio(scope.row.value,scope.row.last) }}</div>
                 </template>
                </el-table-column>
            </el-table>
      </div>
      <div class="form-box">
      <el-form-item prop="infoMsg.leader" label="单位负责人：" label-width="400px" :rules="rules.leader">
           <el-input style="width: 350px;" v-model="form.infoMsg.leader" :disabled="isCheck" placeholder="请输入单位负责人" />
      </el-form-item>
      <el-form-item prop="infoMsg.statistical" label="统计负责人：" label-width="400px" :rules="rules.statistical">
           <el-input  style="width: 350px;" v-model="form.infoMsg.statistical" :disabled="isCheck" placeholder="请输入统计负责人" />
      </el-form-item>
      <el-form-item prop="infoMsg.preparer" label="填表人：" label-width="400px" :rules="rules.preparer">
           <el-input  style="width: 350px;" v-model="form.infoMsg.preparer" :disabled="isCheck" placeholder="请输入填表人" />
      </el-form-item>
      <el-form-item prop="infoMsg.tel" label="联系电话：" label-width="400px" :rules="rules.tel">
           <el-input  style="width: 350px;" v-model="form.infoMsg.tel" :disabled="isCheck" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item prop="infoMsg.phone" label="手机号码：" label-width="400px" :rules="rules.phone">
           <el-input  style="width: 350px;" v-model.number="form.infoMsg.phone" :disabled="isCheck" placeholder="请输入手机号码" />
      </el-form-item>
      <el-form-item prop="infoMsg.date" label="报出日期：" label-width="400px" :rules="rules.date">
        <el-date-picker
         :disabled="isCheck"
          v-model="form.infoMsg.date"
          placeholder="时间"
          style="width: 350px;"
          format="YYYY-MM-DD"
          type="date"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
     </div>
    </el-form>
      </el-tab-pane>
      <el-tab-pane :label="users.userRole=='1'?'文件查看':'文件上传'" name="second">
        <upfiles  :id="id"/>
      </el-tab-pane>
    </el-tabs>
      
</template>
<style scoped>
.table-box{
    width: 100%;
    box-sizing: border-box;
    border: 1px solid rgb(102, 102, 102);
    margin-top: 20px;
} 
.agencyName{
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
    border-bottom: 1px solid rgb(102, 102, 102);
    height: 60px;
}
.msg-box{
    display: flex;
    justify-content: right;
    border-bottom: 1px solid black;
    border-top: 1px solid rgb(102, 102, 102);
    padding: 30px 0;
}
.table-title{
    text-align: center;
    font-size: 24px;
    background-color: #FF0000;
    line-height: 50px;
    color: #ffffff;
    border-bottom: 1px solid rgb(102, 102, 102);
}
.bth-report{
    width: 100%;
    display: flex;
    justify-content: right;
}
.msg-input{
    box-sizing: border-box;
}
.form-box{
    width: 100%;
    display: flex;
    flex-flow: wrap;
    border: 1px solid rgb(102, 102, 102);
    box-sizing: border-box;
    justify-content: space-between;
    padding-top: 20px;
}

</style>
